<template>
  <div class="search">
    <!-- 导航栏 -->
    <van-nav-bar
      title="搜索中心"
      left-arrow
      @click-left="$router.back()"
    />

    <!-- 搜索栏 -->
    <van-search
      v-model.trim="key"
      @input="onInput"
      shape="round"
      show-action
      placeholder="请输入搜索关键词"
      @search="onSearch"
    >
      <template #action>
        <div @click="onSearch">搜索</div>
      </template>
    </van-search>

    <!-- 历史记录区域 -->
    <van-cell-group v-if="!key">
      <van-cell title="历史记录" />
      <van-cell
        :title="item"
        v-for="item,index in historyList"
        :key="index"
        @click="$router.push({ name: 'result', query: {  key: item } })"
      />
    </van-cell-group>

    <!-- 联想区域 -->
    <van-cell-group v-else>
      <!-- <van-cell
        title="联想词汇"
        icon="search"
      /> -->
      <van-cell
        v-for="item,index in colorSuggests"
        :key="index"
        icon="search"
        @click="$router.push({ name: 'result', query: {  key: suggestList[index] } })"
      >
        <div v-html="item"></div>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { suggestAPI } from '@/api'
export default {
  data() {
    return {
      key: "",
      suggestList: [], // 搜索联想词
      time: 0,
      historyList: JSON.parse(window.localStorage.getItem('history')) || []//存放历史记录
    };
  },
  computed: {
    colorSuggests() {
      // 遍历搜索联想的数组，产生一个新数组
      // 搜索到this.key就正则变红
      let reg = new RegExp(this.key, 'ig')
      console.log('reg:', reg);
      console.log('this.suggestList:', this.suggestList);
      if (this.suggestList.length === 0 || this.suggestList[0] === null) return
      return this.suggestList.map(v =>
        // 标签新建一个原生标签来v-html
        v.replace(reg, `<span style="color:red;">${this.key}</span>`)
      )
    }
  },
  methods: {
    // 搜索的点击事件
    // onInput搜索框输入事件
    onInput() {
      // 拿到输入的内容，发请求获取联想词汇
      clearTimeout(this.timer)
      if (this.key) {
        this.timer = setTimeout(async () => {
          const res = await suggestAPI({ q: this.key })

          this.suggestList = res.data.data.options;

          console.log('res:', res);
          console.log('suggestList:', this.suggestList);
        }, 200);
      }
    },
    onSearch() {
      // 点击搜索后
      if (this.key) {
        if (!this.historyList.includes(this.key)) {
          this.historyList.unshift(this.key)
        }
        window.localStorage.setItem('history', JSON.stringify(this.historyList))
        this.$router.push({
          name: 'result',
          query: {
            key: this.key
          }
        })
      }
    }
  },
};
</script>

<style>
</style>